package com.leesche.zcsp.node.utils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;

/*
 '寰俊鏀粯鏈嶅姟鍣ㄧ鍚嶆敮浠樿姹傝姹傜被
 '============================================================================
 'api璇存槑锛�
 'init(app_id, app_secret, partner_key, app_key);
 '鍒濆鍖栧嚱鏁帮紝榛樿缁欎竴浜涘弬鏁拌祴鍊硷紝濡俢mdno,date绛夈�
 'setKey(key_)'璁剧疆鍟嗘埛瀵嗛挜
 'getLasterrCode(),鑾峰彇鏈�悗閿欒鍙�
 'GetToken();鑾峰彇Token
 'getTokenReal();Token杩囨湡鍚庡疄鏃惰幏鍙朤oken
 'createMd5Sign(signParams);鐢熸垚Md5绛惧悕
 'genPackage(packageParams);鑾峰彇package鍖�
 'createSHA1Sign(signParams);鍒涘缓绛惧悕SHA1
 'sendPrepay(packageParams);鎻愪氦棰勬敮浠�
 'getDebugInfo(),鑾峰彇debug淇℃伅
 '============================================================================
 '*/
public class RequestHandler {
	/** Token鑾峰彇缃戝叧鍦板潃鍦板潃 */
	private String tokenUrl;
	/** 棰勬敮浠樼綉鍏硊rl鍦板潃 */
	private String gateUrl;
	/** 鏌ヨ鏀粯閫氱煡缃戝叧URL */
	/** 鍟嗘埛鍙傛暟 */
	private String appid;
	private String appkey;
	private String partnerkey;
	private String appsecret;
	private String key;
	/** 璇锋眰鐨勫弬鏁�*/
	private SortedMap parameters;
	/** Token */
	private String Token;
	private String charset;
	/** debug淇℃伅 */
	private String debugInfo;
	private String last_errcode;

	private String encode;
	/**
	 * 鍒濆鏋勯�鍑芥暟銆�
	 * 
	 * @return
	 */
	public RequestHandler(String encode) {
		this.last_errcode = "0";
		//this.charset = "GBK";
		this.charset = "UTF-8";
		this.parameters = new TreeMap();
		// 楠岃瘉notify鏀粯璁㈠崟缃戝叧
		this.encode = encode;
	}

	/**
	 * 鍒濆鍖栧嚱鏁般�
	 */
	public void init(String app_id, String app_secret,	String partner_key) {
		this.last_errcode = "0";
		this.Token = "token_";
		this.debugInfo = "";
		this.appid = app_id;
		this.partnerkey = partner_key;
		this.appsecret = app_secret;
		this.key = partner_key;
	}

	public void init() {
	}

	/**
	 * 鑾峰彇鏈�悗閿欒鍙�
	 */
	public String getLasterrCode() {
		return last_errcode;
	}

	/**
	 *鑾峰彇鍏ュ彛鍦板潃,涓嶅寘鍚弬鏁板�
	 */
	public String getGateUrl() {
		return gateUrl;
	}

	/**
	 * 鑾峰彇鍙傛暟鍊�
	 * 
	 * @param parameter
	 *            鍙傛暟鍚嶇О
	 * @return String
	 */
	public String getParameter(String parameter) {
		String s = (String) this.parameters.get(parameter);
		return (null == s) ? "" : s;
	}

	
	 //璁剧疆瀵嗛挜
	
	public void setKey(String key) {
		this.partnerkey = key;
	}
	//璁剧疆寰俊瀵嗛挜
	public void  setAppKey(String key){
		this.appkey = key;
	}
	
	// 鐗规畩瀛楃澶勭悊
	public String UrlEncode(String src) throws UnsupportedEncodingException {
		return URLEncoder.encode(src, this.charset).replace("+", "%20");
	}

	// 鑾峰彇package鐨勭鍚嶅寘
	public String genPackage(SortedMap<String, String> packageParams)
			throws UnsupportedEncodingException {
		String sign = createSign(packageParams);

		StringBuffer sb = new StringBuffer();
		Set es = packageParams.entrySet();
		Iterator it = es.iterator();
		while (it.hasNext()) {
			Map.Entry entry = (Map.Entry) it.next();
			String k = (String) entry.getKey();
			String v = (String) entry.getValue();
			sb.append(k + "=" + UrlEncode(v) + "&");
		}

		// 鍘绘帀鏈�悗涓�釜&
		String packageValue = sb.append("sign=" + sign).toString();
//		System.out.println("UrlEncode鍚�packageValue=" + packageValue);
		return packageValue;
	}

	/**
	 * 鍒涘缓md5鎽樿,瑙勫垯鏄�鎸夊弬鏁板悕绉癮-z鎺掑簭,閬囧埌绌哄�鐨勫弬鏁颁笉鍙傚姞绛惧悕銆�
	 */
	public String createSign(SortedMap<String, String> packageParams) {
		StringBuffer sb = new StringBuffer();
		Set es = packageParams.entrySet();
		Iterator it = es.iterator();
		while (it.hasNext()) {
			Map.Entry entry = (Map.Entry) it.next();
			String k = (String) entry.getKey();
			String v = (String) entry.getValue();
			if (null != v && !"".equals(v) && !"sign".equals(k)
					&& !"key".equals(k)) {
				sb.append(k + "=" + v + "&");
			}
		}
		sb.append("key=" + this.getKey());
		System.out.println("md5 sb:" + sb+"key="+this.getKey());
		String sign = MD5Util.MD5Encode(sb.toString(), this.charset)
				.toUpperCase();
		System.out.println("packge绛惧悕:" + sign);
		return sign;

	}
	/**
	 * 鍒涘缓package绛惧悕
	 */
	public boolean createMd5Sign(String signParams) {
		StringBuffer sb = new StringBuffer();
		Set es = this.parameters.entrySet();
		Iterator it = es.iterator();
		while (it.hasNext()) {
			Map.Entry entry = (Map.Entry) it.next();
			String k = (String) entry.getKey();
			String v = (String) entry.getValue();
			if (!"sign".equals(k) && null != v && !"".equals(v)) {
				sb.append(k + "=" + v + "&");
			}
		}

		// 绠楀嚭鎽樿
		String enc = encode;
		String sign = MD5Util.MD5Encode(sb.toString(), enc).toLowerCase();

		String tenpaySign = this.getParameter("sign").toLowerCase();

		// debug淇℃伅
		this.setDebugInfo(sb.toString() + " => sign:" + sign + " tenpaySign:"
				+ tenpaySign);

		return tenpaySign.equals(sign);
	}

	

    //杈撳嚭XML
	   public String parseXML() {
		   StringBuffer sb = new StringBuffer();
	       sb.append("<xml>");
	       Set es = this.parameters.entrySet();
	       Iterator it = es.iterator();
	       while(it.hasNext()) {
				Map.Entry entry = (Map.Entry)it.next();
				String k = (String)entry.getKey();
				String v = (String)entry.getValue();
				if(null != v && !"".equals(v) && !"appkey".equals(k)) {
					
					sb.append("<" + k +">" + getParameter(k) + "</" + k + ">\n");
				}
			}
	       sb.append("</xml>");
			return sb.toString();
		}

	/**
	 * 璁剧疆debug淇℃伅
	 */
	protected void setDebugInfo(String debugInfo) {
		this.debugInfo = debugInfo;
	}
	public void setPartnerkey(String partnerkey) {
		this.partnerkey = partnerkey;
	}
	public String getDebugInfo() {
		return debugInfo;
	}
	public String getKey() {
		return partnerkey;
	}

}
